package tw.com.msig.spring.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import tw.com.msig.spring.hibernate.entity.Role;
import tw.com.msig.spring.hibernate.service.RoleService;

@Controller
// <bean id="userController" class="tw.com.msig.spring.web.UserController"/>
@RequestMapping("/roles")
public class RoleController {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RoleService roleService;

	@RequestMapping("/list")
	public String listPage(Model uiModel) {

		log.debug("list");

		uiModel.addAttribute("roles", roleService.getAll());

		return "/roleList"; // -> /WEB-INF/pages/users/list.jsp
	}

	@RequestMapping("/add")
	public String addPage() {
		return "/roleAdd"; // -> /WEB-INF/pages/users/add.jsp
	}

	@RequestMapping("/insert")
	public String insert(Role role) {
		// log.debug("account={} , name={}",account, name);
		//
		// role role = new role();
		// role.setAccount(account);
		// role.setName(name);

		log.debug("role={}", role);

		roleService.insert(role);

		return "redirect:/roles/add";
	}

	@RequestMapping("/delete")
	public String delete(Long id, Model uiModel) {
		log.debug("to delete id={}", id);

		roleService.delete(id);

		return listPage(uiModel);
	}

	@RequestMapping("/edit")
	public String editPage(Long id, Model uiModel) {

		Role role = roleService.getOne(id);

		uiModel.addAttribute("role", role);

		return "/roleEdit"; // -> /WEB-INF/pages/users/edit.jsp
	}

	@RequestMapping("update")
	public String update(Role role, Model uiModel) {
		// role role = new role();
		// role.setId(id);
		// role.setName(name);

		roleService.update(role);

		return editPage(role.getId(), uiModel);
	}

}
